# -*- coding: utf-8 -*-

#    Copyright (C) 2005, 2006, 2007 2008, 2009, 2010 by Promotux
#                        di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of Promogest.

#    Promogest is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    Promogest is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with Promogest.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
try:
    from collections import OrderedDict
except:
    from ordereddict import OrderedDict
from promogest.ui.utils import *
from promogest.lib.webutils import *
#from promogest.lib.HtmlHandler import renderTemplate
from promogest.lib.page import Page
from promogest.lib.webutils import renderTemplate
from promogest.dao.Cliente import Cliente
from promogest.dao.PersonaGiuridica import \
                                        PersonaGiuridica_ as PersonaGiuridica
from promogest.dao.StaticPages import StaticPages
from promogest.modules.InfoPeso.dao.TipoTrattamento import TipoTrattamento


@expose("/questionario_introduttivo")
def creaQuestionario(req):
    trattamenti = TipoTrattamento().select(batchSize=None)

    dao = Cliente().getRecord(id=req.form.get("id_cliente"))
    if req.form.get("anteprima"):
        return __anteprimaMetodo(req, dao=dao, action=action)
    pageData = {'file': 'questionario_introduttivo',
        "trattamenti": trattamenti,
        "dao": dao,
        "daoCliente": dao,
        "qipage": "qipage",
        "now": datetime.datetime.now(),
        }
    return Page(req).render(pageData)


@expose("/anteprima_metodo")
def anteprimaMetodo(req):
    from  xhtml2pdf import pisa
    correctDict = {}
    # correttamente abbiniamo il nome al proprio valore del campo del form
    for r in req.form.to_dict():
        if "name" in r:
            correctDict[req.form.get(r)] = req.form.get(r.replace("name",
                                                                 "value"))

    dao = Cliente().getRecord(id=correctDict["id_cliente"])
    pagine = StaticPages().select(batchSize=None)
    pdict = {}
    for pag in pagine:
        pdict[pag.permalink] = pag

    pageData = {'file': 'anteprima_metodo',
        "pagine": pdict,
        "correctDict": correctDict,
        "dati_form": req.form.to_dict(),
        "dao": dao,
        "daoCliente": dao
        }
    pageData['dao_pg'] = None

    if getUserFromId(req):
        pg = PersonaGiuridica().select(idUser=getUserFromId(req).id)
        if pg:
            pageData['dao_pg'] = pg[0]
    if str(req.form.get("stampa")) == str(1):
        pageData["USER"] = getUserFromId(req)
        pageData['nameuser'] = getUsernameFromId(req)
        html = renderTemplate(pageData)
        #print "HTMLLLLLL", html
        try:
            g = file(os.path.expanduser('~') + os.sep +"infopeso/core/templates/pdfs/metodo_giustopeso.pdf", "wb")
        except:
            g = file("/home/promo/infopeso/infopeso/core/templates/pdfs/metodo_giustopeso.pdf", "wb")

        pisa.CreatePDF(str(html), g)
        g .close()
        pageData = {'file': 'download_pdf_no_redirect',
            "hf": "/templates/pdfs/" \
                        + "metodo_giustopeso" \
                        + ".pdf?" \
                        + str(datetime.datetime.now()),
            "now": datetime.datetime.now()}
    return Page(req).render(pageData)


